import radix

class node(object):
   def __init__(self, data):
      self._data = data

   def __str__(self):
      return self._data.prefix

   @property
   def version(self):
      return self._data.data["version"]


class trie(object):
   def __init__(self):
      self._tree = radix.Radix()

   def add(self, ipaddress, nexthop = None):
      rnode = self._tree.add(str(ipaddress))
      rnode.data["version"] = ipaddress.version
      if nexthop:
         rnode.data["nexthop"] = nexthop

   def lookup(self, ipaddress, best = True):
      address = None
      if isinstance(ipaddress, (str, unicode)):
         address = ipaddress
      else:
         address = str(ipaddress)

      retval = self._tree.search_best(address)
      return node(retval)

   def __iter__(self):
      for nodes in self._tree.nodes():
         yield node(nodes)
